//
//  LSFastFile.swift
//  LSFileManager
//
//  Created by LuckyStrike on 2017/11/8.
//  Copyright © 2017年 LuckyStrike. All rights reserved.
//

import Foundation

/*
 TODO:打印错误信息 方法名，行数，完整目录
 */

// MARK:-快速获取主文件夹路径
let FastDocument : String = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let FastLibrary : String = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true).last!
let FastCaches : String = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).last!
let FastTmp : String = NSTemporaryDirectory()

extension String {
// MARK:-快速创建文件夹和文件目录路径
    public func fileFC(_ name: String) -> String {
        let tmp = self + "/" + name
        return tmp
    }
    
    public func folderFC(_ name: String) -> String {
        let tmp = self + "/" + name
        return tmp
    }
    // MARK:-读取数据
    public func readToDataFC() -> Data? {
        guard checkExistPath() else { return nil }
        return NSData.init(contentsOfFile: self) as Data?
    }
    
    public func readToDicFC() -> [String:Any]? {
        guard checkExistPath() else { return nil }
        return NSDictionary.init(contentsOfFile: self) as? [String:Any]
    }
    
    public func readToArrFC() -> [Any]? {
        guard checkExistPath() else { return nil }
        return NSArray.init(contentsOfFile: self) as? [Any]
    }
    // MARK:-存入数据
    public func saveFC(data: Data) -> Bool {
        createFolderFC()
        return (data as NSData).write(toFile: self, atomically: true)
    }

    public func saveFC(dic: [String:Any]) -> Bool {
        createFolderFC()
        return (dic as NSDictionary).write(toFile: self, atomically: true)
    }

    public func saveFC(arr: [Any]) -> Bool {
        createFolderFC()
        return (arr as NSArray).write(toFile: self, atomically: true)
    }
}

// MARK:-功能
extension String {
    // MARK:-获取路径文件或文件夹的大小
    public func sizeFC() -> Float {
        guard let check = checkFolderOrFile() else { return 0 }
        if check {
            var tmp : Float = self.fileSize()
            guard let rArr = self.contentsFC() else { return tmp }
            for item in rArr {
                let tmpPath = self + "/" + item
                tmp += tmpPath.fileSize()
            }
            return tmp
        }else{
            return self.fileSize()
        }
    }
    // MARK:-获取路径文件夹的内容
    public func contentsFC() -> [String]? {
        guard checkExistPath() else { return nil }
        guard checkFolderOrFile() ?? false else { return nil }
        return try? FileManager.default.contentsOfDirectory(atPath: self)
    }
    // MARK:-清理文件夹或文件的内存
    public func clearFC() -> Void {
        try? FileManager.default.removeItem(atPath: self)
    }
    // MARK:-获取文件夹或文件上一次修改到现在的时间
    public func lastedFC() -> TimeInterval {
        guard FileManager.default.fileExists(atPath: self) else { return 0 }
        let dic = try? FileManager.default.attributesOfItem(atPath: self)
        guard let tempDic = dic else { return 0 }
        let saveDate = tempDic[FileAttributeKey.modificationDate] as? Date
        guard let tempDate = saveDate else { return 0 }
        return Date().timeIntervalSince(tempDate)
    }
}
// MARK:-检测
extension String {
    // MARK:-检测目录有效性
    func checkVaildPath() -> Bool {
        let factor = contains(NSHomeDirectory())
        if factor { return true }
        return false
    }
    // MARK:-检测目录是否存在
    func checkExistPath() -> Bool {
        guard checkVaildPath() else { return false }
        let exists = FileManager.default.fileExists(atPath: self)
        if exists {
            return true
        }
        return false
    }
    // MARK:-创建对应路径目录
    func createFolderFC() -> Void {
        guard checkFullPath() else { return }
        try? FileManager.default.createDirectory(atPath: self.foldersName()!, withIntermediateDirectories: true, attributes: nil)
    }
    
    fileprivate func checkFullPath() -> Bool {
        let docuCheck = contains(FastDocument + "/")
        let libCheck = contains(FastLibrary + "/")
        let cacCheck = contains(FastCaches + "/")
        let tmpCheck = contains(FastTmp + "/")
        return docuCheck || libCheck || cacCheck || tmpCheck
    }
    
    fileprivate func checkFolderOrFile() -> Bool? {
        guard checkExistPath() else { return nil }
        let att = try? FileManager.default.attributesOfItem(atPath: self)
        guard let rAtt = att else { return nil }
        
        let ft = rAtt[FileAttributeKey.type] as? FileAttributeType
        
        guard let rft = ft else { return nil }
        
        if rft == FileAttributeType.typeDirectory {
            return true
        }
        return false
    }
}
// MARK:-私有工具
extension String {
    fileprivate func fileSize() -> Float {
        let att = try? FileManager.default.attributesOfItem(atPath: self)
        guard let rAtt = att else { return 0 }
        let size = rAtt[FileAttributeKey.size] as? Float
        guard let rSize = size else { return 0 }
        return rSize
    }
    
    fileprivate func fileName() -> String? {
        guard checkFullPath() else { return nil }
        let file = self.components(separatedBy: "/").last
        guard var rFile = file else { return nil }
        let fileNameArr = rFile.components(separatedBy: ".")
        if fileNameArr.count < 2 {
            return fileNameArr.first
        }else{
            let last = fileNameArr.last!
            let index = rFile.range(of: ".\(last)")!
            rFile.removeSubrange(index)
            return rFile
        }
    }
    
    fileprivate func fileTypeName() -> String? {
        guard checkFullPath() else { return nil }
        let file = self.components(separatedBy: "/").last
        guard let rFile = file else { return nil }
        let fileNameArr = rFile.components(separatedBy: ".")
        if fileNameArr.count < 2 {
            return nil
        }else {
            return fileNameArr.last!
        }
    }
    
    fileprivate func foldersName() -> String? {
        guard checkFullPath() else { return nil }
        var fullPath = self
        let file = self.components(separatedBy: "/").last!
        let index = fullPath.range(of: "/\(file)")!
        fullPath.removeSubrange(index)
        return fullPath
    }
}

//    public func saveFC(value: Any) -> Bool {
//        createFolderFC()
//        switch value {
//        case let value as Data:
//            return (value as NSData).write(toFile: self, atomically: true)
//        case let value as [String:Any]:
//            return (value as NSDictionary).write(toFile: self, atomically: true)
//        case let value as [Any]:
//            return (value as NSArray).write(toFile: self, atomically: true)
//        default:
//            return false
//        }
//    }
